<template>
  <div class="upload">
    <el-upload
      class="avatar-uploader"
      ref="uploadref"
      :disabled="isopenselect"
      list-type="picture-card"
      :limit="limit"
      :action="action"
      name="files"
      :headers="headerObj"
      :show-file-list="true"
      :on-success="handleAvatarSuccess"
      :on-remove="handleRemove"
      :before-upload="beforeAvatarUpload"
      :on-preview="handlePreview"
      :file-list="Filelist"
      :on-exceed="handleExceed"
      :data="{ fileType: 1, label: label }"
    >
      <template #tip v-if="tip">
        <div class="el-upload__tip">
          {{ tip }}
        </div>
      </template>
      <el-icon
        class="avatar-uploader-icon"
        @click="eluploadclick"
        ref="triggerRef"
        ><Plus
      /></el-icon>
    </el-upload>

    <el-dialog
      v-model="imgdialogVisible"
      width="600px"
      append-to-body
      class="uploadimgDialog"
    >
      <img style="width: 100%" :src="dialogImageUrl" />
    </el-dialog>

    <el-dialog
      v-model="uploadDialogVisible"
      title="选择上传来源"
      width="656"
      align-center
      @close="uploadClose"
    >
      <div class="uploadbody">
        <div class="top">
          <div class="left">
            <el-radio-group v-model="radio1" @change="handleRadioChange">
              <el-radio label="1" size="large">AECMate 365</el-radio>
            </el-radio-group>
            <img src="@/assets/images/zyk.png" alt="" />
          </div>
          <div class="right">
            <el-radio-group v-model="radio1" @change="handleRadioChange">
              <el-radio label="2" size="large">本地上传</el-radio>
            </el-radio-group>
            <img src="@/assets/images/bd.png" alt="" />
          </div>
        </div>

        <el-input
          v-if="radio1 == '1'"
          v-model="resourceCode"
          placeholder="请输入资源定位符"
          class="inputss"
          @input="inputUrlCode"
          :validate-event="false"
        >
          <template #suffix
            ><el-icon style="color: rgb(132, 228, 132)" v-if="isConfim"
              ><SuccessFilled
            /></el-icon>
          </template>
        </el-input>
        {{ resFileName }}
      </div>
      <template #footer>
        <div class="dialog-footer" v-if="radio1 == '1'">
          <el-button @click="uploadDialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            :disabled="!isConfim"
            @click="resourceCodeClick"
          >
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, watch } from "vue";
import { ElMessage } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import { getToken } from "@/utils/auth";
import debounce from "lodash/debounce";

import {
  uploadResourceLocationRequest,
  queryResourceLocationRequest,
} from "@/api/file.js";

const emit = defineEmits(["file-uploaded", "file-remove"]);
const props = defineProps({
  uploadId: {
    type: Number,
    default: null,
  },
  tip: {
    type: String,
    default: "",
  },

  limit: {
    type: Number,
    default: 3,
  },
  name: {
    type: String,
  },
  // 显示的附件列表
  Filelist: {
    type: Array,
    default: () => [],
  },
  //标记
  label: {
    type: String,
    default: "",
  },
  //大小
  maxSize: {
    type: Number,
    default: 10,
  },
});

const headerObj = ref({
  Authorization: "Bearer " + getToken(),
});

const action =
  import.meta.env.MODE === "production"
    ? `${
        import.meta.env.VITE_APP_BASE_API
      }/management-admin/file/uploadFileSimple`
    : "/admin/management-admin/file/uploadFileSimple";
const uploadref = ref(null);
const handleAvatarSuccess = (response, uploadFile, uploadFiles) => {
  let resData = {
    id: response.data[0].id,
    name: uploadFile.name,
    path: response.data[0].url,
    size: uploadFile.size,
    uploadId: props.uploadId,
  };
  emit("file-uploaded", resData);
};

const handleRemove = (file, fileList) => {
  file.uploadId = props.uploadId;
  emit("file-remove", file);
};

const beforeAvatarUpload = (rawFile) => {
  const isJPG =
    rawFile.type === "image/jpeg" ||
    rawFile.type === "image/png" ||
    rawFile.type === "image/jpg" ||
    rawFile.type === "image/gif" ||
    rawFile.type === "image/webp";
  if (!isJPG) {
    ElMessage.error("只允许上传图片文件！");
    return false;
  } else if (rawFile.size / 1024 / 1024 > 5) {
    ElMessage.error("图片大小不能超过 5MB!");
    return false;
  }
  return true;
};

//文件长度限制
const handleExceed = (files, fileList) => {
  ElMessage.error(`当前限制选择 ${props.limit} 个文件`);
  return false;
};

let imgdialogVisible = ref(false);
let dialogImageUrl = ref("");
const handlePreview = (file) => {
  imgdialogVisible.value = true;
  dialogImageUrl.value = file.url;
};

// 3-1
const eluploadclick = () => {
  isopenselect.value = true;
  uploadDialogVisible.value = !uploadDialogVisible.value;
};

// dialog框显示隐藏
let uploadDialogVisible = ref(false);

//单选按钮绑定值
let radio1 = ref("");

let isopenselect = ref(false); //是否能狗上传

let resourceCode = ref(""); //资源代码

// 上传按钮的ref
const triggerRef = ref(null);
// 单选按钮切换事件
const handleRadioChange = (value) => {
  console.log(value);
  if (value == 2) {
    isopenselect.value = false;

    nextTick(() => {
      triggerRef.value?.$.vnode.el?.click();
    });
    // isopenselect.value = true;
  }
};
//dialog关闭
const uploadClose = () => {
  radio1.value = "";
  resourceCode.value = "";
  isopenselect.value = false;
  isConfim.value = false;
  resFileName.value = "";
};

//============================================================

//资源代码点击事件
let isConfim = ref(false); //是否能点击确定
let resData = {}; //资源代码
let resFileName = ref(""); //文件名
const inputChange = async (val) => {
  if (!val) return;

  try {
    const res = await queryResourceLocationRequest({ positionId: val });
    if (res.code == 200) {
      resFileName.value = res.data.fileName;
      let isPass = isAccept(res.data.fileName, res.data.fileSize);

      if (isPass) {
        isConfim.value = true;
        console.log(res.data);
        resData.name = res.data.fileName;
        resData.size = res.data.fileSize;
        console.log(resData);
      }
    }
    console.log(res);
  } catch (error) {
    isConfim.value = false;
    resFileName.value = "";
  }
};

//判断传入的后缀名和大小是否符合要求
const isAccept = (fileName, fileSize) => {
  let temp = fileName.split(".");
  const TemprawType = temp[temp.length - 1]; //获取格式
  const rawType = TemprawType.toLowerCase(); //强制转换成小写 来应对 文件大写的错误
  const isJPG =
    rawType === "jpeg" ||
    rawType === "png" ||
    rawType === "jpg" ||
    rawType === "gif" ||
    rawType === "webp";
  const isLt = fileSize / 1024 / 1024 < props.maxSize;

  if (!isJPG) {
    ElMessage.error(`上传文件只能是图片!`);
    uploadref.value.clearFiles();
    return false;
  } else if (!isLt) {
    ElMessage.error(`上传的附件大小不能超过 ${props.maxSize}MB!`);
    uploadref.value.clearFiles();
    return false;
  }
  return true;
};

const inputUrlCode = debounce(inputChange, 500);

const resourceCodeClick = () => {
  const formData = new FormData();
  formData.append("positionId", resourceCode.value);
  if (resourceCode.value) {
    console.log(resData);
    // emit("file-uploaded", resData);
    uploadResourceLocationRequest(formData).then((res) => {
      console.log(res);
      if (res.code == 200) {
        uploadDialogVisible.value = false;
        console.log(res);
        resData.id = res.data.repositoryTreeId;
        resData.path = res.data.path;
        // isopenselect.value = true;
        if (props.uploadId) {
          resData.uploadId = props.uploadId;
        }

        console.log(resData);
        emit("file-uploaded", resData);
      }
    });
  } else {
    ElMessage.error("请输入资源定位符");
  }
};
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.uploadbody {
  .top {
    display: flex;
  }
  img {
    width: 300px;
    height: 240px;
  }
  .inputss {
    margin-top: 14px;
  }
}
</style>
